package com.ylwl.datacenterdemo.controller;

import com.ylwl.datacenterdemo.service.ExcelImportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@RestController
@RequestMapping("/test")
@RequiredArgsConstructor
@Slf4j
public class TestExcelImportController {
    
    private final ExcelImportService excelImportService;
    
    /**
     * 测试上传并导入Excel文件
     * @param file Excel文件
     * @return 导入结果
     */
    @PostMapping("/upload-and-import")
    public String uploadAndImportExcel(@RequestParam("file") MultipartFile file) {
        try {
            // 创建临时文件
            Path tempDir = Paths.get("temp");
            if (!Files.exists(tempDir)) {
                Files.createDirectories(tempDir);
            }
            
            Path tempFile = tempDir.resolve(file.getOriginalFilename());
            Files.copy(file.getInputStream(), tempFile, StandardCopyOption.REPLACE_EXISTING);
            
            // 导入Excel数据
            log.info("开始导入Excel文件: {}", file.getOriginalFilename());
            excelImportService.importExcelToDatabase(tempFile.toString());
            
            // 删除临时文件
            Files.delete(tempFile);
            
            return "Excel导入成功";
        } catch (IOException e) {
            log.error("文件处理失败: ", e);
            return "文件处理失败: " + e.getMessage();
        } catch (Exception e) {
            log.error("Excel导入失败: ", e);
            return "Excel导入失败: " + e.getMessage();
        }
    }
}